<template>
   <div class="flex justify-center items-center min-h-screen">
      <div class="border-1 w-120 h-75">
         <lay-form :model="validateModel" ref="layFormRef" required>
            <p class="flex justify-center text-2xl font-bold mt-4">小高权限管理系统</p>
            <lay-form-item class="mt-4 mr-6" label="用户名" prop="username">
               <lay-input v-model="validateModel.username" prefix-icon="layui-icon-username"></lay-input>
            </lay-form-item>
            <lay-form-item class="mr-6" label="密码" prop="password">
               <lay-input v-model="validateModel.password" type="password" prefix-icon="layui-icon-password" autocomplete password></lay-input>
            </lay-form-item>
            <lay-form-item class="mr-6" label="验证码" prop="captcha">
               <lay-space>
                  <lay-input v-model="validateModel.captcha" prefix-icon="layui-icon-vercode"></lay-input>
                  <img :src="captchaImg" class="w-[170px] h-[40px]" @click="getCaptcha">
               </lay-space>
            </lay-form-item>
            <lay-form-item>
               <lay-button type="primary" @click="login">登录</lay-button>
            </lay-form-item>
         </lay-form>
      </div>
   </div>
</template>

<script setup>
import { layer } from "@layui/layer-vue"
import { ref, reactive, onMounted } from 'vue'
import { loginReq, captchaReq } from "@/api/login.js"
import {useRouter} from 'vue-router'
import { setToken } from "@/utils/token"
const router = useRouter();

/**
 * 登录
 */
const validateModel = reactive({
   username: "",
   password: "",
   captcha: "",
   uuid: ""
})

const layFormRef = ref()

const login = () => {
   layFormRef.value.validate((isValidate, model, errors) => {
      if (isValidate) {
         loginReq(validateModel).then(res => {
            if(res.data.code ==200){
               setToken(res.data.data)
               layer.msg(res.data.message, { icon : 1, time: 1000})
               router.push("/home");
            }else{
               layer.msg(res.data.message, { icon : 2, time: 1000})
            }
         })
      }
   });
}

/**
 * 初始化验证码
 */
onMounted(() => {
   getCaptcha();
})

/**
 * 获取验证码
 */
const captchaImg = ref("")
const getCaptcha = () => {
   captchaReq().then(res => {
      if (res.data.code == 200) {
         captchaImg.value = "data:image/jpg;base64," + res.data.data.captcha
         validateModel.uuid = res.data.data.uuid
      }
   })
}
</script>